function getQuery(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split('&');
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split('=');
    if (pair[0] == variable) {
      return pair[1];
    }
  }
  return false;
}

var info = {
  fileInput: $('.input-file'),
  delBtn: $('.del-img'),
  init: function () {
    this.initBKInfo();
    this.fileChange();
    this.delImg();
    this.initSubmit();
    this.initSelects();
    $('.fee').find('.fee-flag').prop('disabled', true);
    $('.selectpicker').selectpicker({
      selectedText: 'cat',
    });
  },
  initSelects() {
    $.ajax({
      url: baseUrl + 'education/queryClasssList',
      method: 'Post',
      headers: {
        Authorization: JSON.parse(localStorage.getItem('userInfo')).token,
      },
      success: function (data) {
        var html_ = '<option value="0">请选择</option>';
        for (var i = 0; i < data.length; i++) {
          html_ += `<option value=${data[i].id}>${data[i].classs}</option>`;
        }
        $('.classes').html(html_);
      },
    });
    $.ajax({
      url: baseUrl + 'education/queryModeList',
      async: false,
      method: 'Post',
      headers: {
        Authorization: JSON.parse(localStorage.getItem('userInfo')).token,
      },
      success: function (data) {
        var html_ = '<option value="0">请选择</option>';
        for (var i = 0; i < data.length; i++) {
          html_ +=
            '<option  value="' +
            data[i].id +
            '" >' +
            data[i].mode +
            '</option>';
        }
        // $("#baokao-studyMode").html(html_);
        $('.studyMode').html(html_);
      },
    });
    $.ajax({
      url: baseUrl + 'education/queryEducationList',
      async: false,
      method: 'Post',
      headers: {
        Authorization: JSON.parse(localStorage.getItem('userInfo')).token,
      },
      success: function (data) {
        var html_ = '<option value="0">请选择</option>';
        for (var i = 0; i < data.length; i++) {
          html_ +=
            '<option  value="' +
            data[i].id +
            '" >' +
            data[i].educationName +
            '</option>';
        }
        $('.educationLevel').html(html_);
      },
    });

    $.ajax({
      url: baseUrl + 'education/queryProfessionalSeriesList',
      async: false,
      method: 'Post',
      headers: {
        Authorization: JSON.parse(localStorage.getItem('userInfo')).token,
      },
      success: function (data) {
        var html_ = '<option value="0">请选择</option>';
        for (var i = 0; i < data.length; i++) {
          html_ +=
            '<option  value="' +
            data[i].id +
            '" >' +
            data[i].professionalSeries +
            '</option>';
        }
        $('.professional-series').html(html_);
      },
    });

    // 职业批次
    $.ajax({
      url: baseUrl + 'education/queryBatchList',
      method: 'Post',
      data: {
        trainType: 'occupation',
      },
      success: function (data) {
        var html_ = '<option value="0">请选择</option>';
        for (var i = 0; i < data.length; i++) {
          html_ +=
            '<option  value="' +
            data[i].id +
            '" >' +
            data[i].batch +
            '</option>';
        }
        $('#zy-pc').html(html_);
      },
    });

    // 职称批次
    $.ajax({
      url: baseUrl + 'education/queryBatchList',
      method: 'Post',
      data: {
        trainType: 'title',
      },
      success: function (data) {
        var html_ = '<option value="0">请选择</option>';
        for (var i = 0; i < data.length; i++) {
          html_ +=
            '<option  value="' +
            data[i].id +
            '" >' +
            data[i].batch +
            '</option>';
        }
        $('#zc-pc').html(html_);
      },
    });

    // 培训批次
    $.ajax({
      url: baseUrl + 'education/queryBatchList',
      method: 'Post',
      data: {
        trainType: 'train',
      },
      success: function (data) {
        var html_ = '<option value="0">请选择</option>';
        for (var i = 0; i < data.length; i++) {
          html_ +=
            '<option  value="' +
            data[i].id +
            '" >' +
            data[i].batch +
            '</option>';
        }
        $('#px-pc').html(html_);
      },
    });

    $.ajax({
      url: baseUrl + 'education/queryOccupationList',
      async: false,
      method: 'Post',
      headers: {
        Authorization: JSON.parse(localStorage.getItem('userInfo')).token,
      },
      success: function (data) {
        var html_ = '<option value="0">请选择</option>';
        for (var i = 0; i < data.length; i++) {
          html_ +=
            '<option  value="' +
            data[i].id +
            '" >' +
            data[i].occupationName +
            '</option>';
        }
        $('.myeducation').html(html_);
      },
    });
    $.ajax({
      url: baseUrl + 'education/queryTitleList',
      async: false,
      method: 'Post',
      headers: {
        Authorization: JSON.parse(localStorage.getItem('userInfo')).token,
      },
      success: function (data) {
        var html_ = '<option value="0">请选择</option>';
        for (var i = 0; i < data.length; i++) {
          html_ +=
            '<option  value="' +
            data[i].id +
            '" >' +
            data[i].titleName +
            '</option>';
        }
        $('.job-title').html(html_);
      },
    });
    $.ajax({
      url: baseUrl + 'education/queryTrainList',
      async: false,
      method: 'Post',
      headers: {
        Authorization: JSON.parse(localStorage.getItem('userInfo')).token,
      },
      success: function (data) {
        var html_ = '<option value="0">请选择</option>';
        for (var i = 0; i < data.length; i++) {
          html_ +=
            '<option  value="' +
            data[i].id +
            '" >' +
            data[i].trainName +
            '</option>';
        }
        $('.myTrain').html(html_);
      },
    });
  },
  initBKInfo() {
    // 根据查询字符串info，来判断显示哪个报考信息
    const type = getQuery('info');
    if (type === 'xl') {
      // 学历
      localStorage.setItem('name', '学生管理/学历提升');
      $('#xl-info').show();
      $('#xueli').show();
    } else if (type === 'zy') {
      // 职业
      localStorage.setItem('name', '学生管理/职业技能');
      $('#zy-info').show();
      $('#zhiye').show();
    } else if (type === 'zc') {
      // 职称
      localStorage.setItem('name', '学生管理/职称评审');
      $('#zc-info').show();
      $('#zhicheng').show();
    } else if (type === 'px') {
      // 培训
      localStorage.setItem('name', '学生管理/执业资格');
      $('#px-info').show();
      $('#peixun').show();
    }
  },
  fileChange: function () {
    var self = this;
    this.fileInput.on('change', function () {
      var files = this.files;
      var id = $(this).attr('id');
      if (files.length) {
        id === 'id-front' && self.uploadFrontImg(files[0]);
        $(this).hide();
        $(this).siblings('.img-con').css('display', 'inline-block');
        self.drawImg($(this).siblings('.img-con').find('img'), files[0]);
      }
    });
  },
  drawImg: function ($el, file) {
    var URL = window.URL || window.webkitURL;
    file.fname = '123123.jpg';
    console.log(file);

    var imgUrl = URL.createObjectURL(file);
    $el.attr('src', imgUrl);
  },
  delImg: function () {
    this.delBtn.on('click', function () {
      $(this).parents('.img-con').hide().siblings('.input-file').show();
      $(this).parents('.img-con').siblings('.input-file')[0].value = '';
    });
  },
  uploadFrontImg: function (file) {
    var formData = new FormData();
    formData.append('headImg', file);
    $.ajax({
      url: baseUrl + 'studentInfo/headImgUpload',
      type: 'POST',
      contentType: false,
      processData: false,
      data: formData,
      headers: {
        Authorization: JSON.parse(localStorage.getItem('userInfo')).token,
      },
      success: function (data) {
        // if (!data) {
        //   $(".front-con").hide();
        //   $("#id-front")[0].value = "";
        //   $("#id-front").show();
        //   return alert("请上传正确的身份证图片");
        // }
        if (data) {
          data = JSON.parse(data);
          data.birthday =
            data.birth.substr(0, 4) +
            '-' +
            data.birth.substr(5, 2) +
            '-' +
            data.birth.substr(6);
          $('#name').val(data.name);
          $('#idno').val(data.num);
          $('#nation').val(data.nationality);
          $('#sex').val(data.sex);
          $('#address').val(data.address);
          $('#birth').val(data.birthday);
          getInfoByIdNo(data.num);
        }
      },
    });
  },
  initSubmit() {
    var self = this;
    $('#save').on('click', function () {
      self.submitInfo('save');
    });
    $('#submit').on('click', function () {
      self.submitInfo('submit');
    });
  },
  submitInfo(flag) {
    var feeTotal = true;
    if (!$('#name').val()) {
      return alert('请输入姓名');
    }
    const idno = $('#idno').val();
    if (!idno) {
      return alert('请输入身份证号码');
    }
    if (
      !/^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(
        idno
      )
    ) {
      return alert('身份证号码有误');
    }

    const phone = $('#phone').val();

    if (!phone) {
      return alert('请输入手机号');
    }

    if (!/^1[3456789]\d{9}$/.test(phone)) {
      return alert('手机号码有误');
    }

    var zong = $('.zong:visible').val();
    var youhui = $('.youhui:visible').val();
    var shijiao = $('.shijiao:visible').val();

    if (!zong) {
      feeTotal = false;
      return alert('请输入总费用');
    }
    if (!youhui) {
      feeTotal = false;
      return alert('请输入优惠费用');
    }
    if (!shijiao) {
      feeTotal = false;
      return alert('请输入实缴费用');
    }

    if (!feeTotal) return;

    // 学历报考信息List
    var studentEducationList = [];
    $('.student-education:visible').each(function (item) {
      // 学习形式
      var studyMode = $(this).find('.studyMode option:selected').text();
      // 学历层次
      var educationName = $(this).find('.educationName option:selected').text();
      // 学校
      var school = $(this).find('.myschool option:selected').text();
      // 报考专业
      var course = $(this).find('.mycourse option:selected').text();
      // 批次
      var batch = $(this).find('.mybatch option:selected').text();
      //

      // 清空-请选择
      studyMode = studyMode === '请选择' ? '' : studyMode;
      educationName = educationName === '请选择' ? '' : educationName;
      school = school === '请选择' ? '' : school;
      course = course === '请选择' ? '' : course;
      batch = batch === '请选择' ? '' : batch;

      if (!studyMode) return alert('学习形式不能为空');
      if (!educationName) return alert('学历层次不能为空');
      if (!school) return alert('学校不能为空');
      if (!course) return alert('报考专业不能为空');
      if (!batch) return alert('批次不能为空');

      if (studyMode || educationName || school || course || batch) {
        studentEducationList.push({
          studyMode: studyMode,
          educationName: educationName,
          schoolName: school,
          majorName: course,
          batch: batch,
          flag: 1,
          id: getId() + window.mobile,
        });
      }
    });
    window.studentEducationList = studentEducationList;

    // 职业报考信息List
    var studentOccupationList = [];
    $('.student-occupation:visible').each(function (item) {
      // 职业技能类别
      var professionalTypes = $(this)
        .find('.professional-type option:selected')
        .text();
      // 报考专业
      var majorName = $(this).find('.majorName option:selected').text();
      // 批次
      var batch = $(this).find('.mybatch option:selected').text();
      // 报考说明
      var applyExplain = $(this).find('.applyExplain').val();

      if (professionalTypes === '请选择') return alert('职业技能类别不能为空');
      if (majorName === '请选择') return alert('报考专业不能为空');
      if (batch === '请选择') return alert('批次不能为空');
      if (!applyExplain) return alert('报考说明不能为空');

      if (
        professionalTypes !== '请选择' ||
        majorName !== '请选择' ||
        batch !== '请选择' ||
        applyExplain
      ) {
        studentOccupationList.push({
          professionalTypes:
            professionalTypes === '请选择' ? '' : professionalTypes,
          majorName: majorName === '请选择' ? '' : majorName,
          applyExplain: applyExplain,
          batch: batch === '请选择' ? '' : batch,
          flag: 1,
          id: getId() + window.mobile,
        });
      }
    });
    window.studentOccupationList = studentOccupationList;

    // 职称报考信息List
    var studentTitleList = [];
    $('.student-title:visible').each(function (item) {
      // 职称等级
      var professionalLevel = $(this)
        .find('.professional-level option:selected')
        .text();
      // 职称系列
      var professionalSeries = $(this)
        .find('.professional-series option:selected')
        .text();
      // 报考专业
      var majorName = $(this).find('.majorName option:selected').text();
      // 批次
      var batch = $(this).find('.mybatch option:selected').text();

      if (professionalLevel === '请选择') return alert('职称等级不能为空');
      if (professionalSeries === '请选择') return alert('职称系列不能为空');
      if (majorName === '请选择') return alert('报考专业不能为空');
      if (batch === '请选择') return alert('批次不能为空');

      if (
        professionalLevel !== '请选择' ||
        professionalSeries !== '请选择' ||
        majorName !== '请选择' ||
        batch !== '请选择'
      ) {
        studentTitleList.push({
          professionalLevel:
            professionalLevel === '请选择' ? '' : professionalLevel,
          professionalSeries:
            professionalSeries === '请选择' ? '' : professionalSeries,
          majorName: majorName === '请选择' ? '' : majorName,
          batch: batch === '请选择' ? '' : batch,
          flag: 1,
          id: getId() + window.mobile,
        });
      }
    });
    window.studentTitleList = studentTitleList;

    // 培训报考信息List
    var studentTrainList = [];
    $('.student-train:visible').each(function (item) {
      // 报考项目
      var applyProject = $(this).find('.apply-project option:selected').text();
      // 考试科目
      var examCourse = [];
      $('.selected').each(function () {
        var selected = $(this).attr('rel');
        var selectedtxt = $(this).text();
        if (selectedtxt !== '请选择') {
          examCourse.push(selectedtxt);
        }
        console.log('==========', selected + '/' + selectedtxt);
      });
      examCourse = examCourse.toString();
      // 班次
      var classs = $(this).find('.classes option:selected').text();
      // 批次
      var batch = $(this).find('.mybatch option:selected').text();
      // 协助报考
      var applyAssist = $(this)
        .next()
        .find('.apply-assist option:selected')
        .text();
      // 开始时间
      var start = $(this).next().find('.start').val();
      // 结束时间
      var end = $(this).next().find('.end').val();

      if (applyProject === '请选择') return alert('报考项目不能为空');
      if (examCourse === '请选择') return alert('考试科目不能为空');
      if (classs === '请选择') return alert('班次不能为空');
      if (batch === '请选择') return alert('批次不能为空');
      if (applyAssist === '请选择') return alert('报考类型不能为空');

      if (
        applyAssist !== '请选择' ||
        classs !== '请选择' ||
        batch !== '请选择' ||
        applyAssist !== '请选择' ||
        start ||
        end
      ) {
        studentTrainList.push({
          teacherId: JSON.parse(localStorage.getItem('userInfo')).account.split(
            '-'
          )[1],
          applyProject: applyProject === '请选择' ? '' : applyProject,
          examCourse: examCourse,
          classs: classs === '请选择' ? '' : classs,
          applyAssist: applyAssist === '请选择' ? '' : applyAssist,
          batch: batch === '请选择' ? '' : batch,
          startDate: start,
          endDate: end,
          flag: 1,
          id: getId() + window.mobile,
        });
      }
    });
    window.studentTrainList = studentTrainList;

    var student = [
      {
        pid: JSON.parse(localStorage.getItem('userInfo')).account.split('-')[1],
        // commitFlag: flag === "save" ? 0 : 1,
        name: $('#name').val(),
        phoneNum: $('#phone').val(),
        idNo: $('#idno').val(),
        nation: $('#nation').val(),
        sex: $('#sex').val(),
        birthday: $('#birth').val(),
        address: $('#address').val(),
        email: $('#email').val(),
        qqNumber: $('#qq').val(),
        workAdress: $('#company').val(),
        // 学历1
        major: $('#zhuanye').val(),
        educationName: $('#educationName option:selected').text(),
        studyMode: $('#studyMode option:selected').val(),
        graduateSchool: $('#school').val(),
        graduateTime: $('#time').val(),
        certificateNumber: $('#certificateNumber').val(),
        // 学历2
        major2: $('#zhuanye2').val(),
        educationName2: $('#educationName2 option:selected').text(),
        studyMode2: $('#studyMode2 option:selected').val(),
        graduateSchool2: $('#school2').val(),
        graduateTime2: $('#time2').val(),
        certificateNumber2: $('#certificateNumber2').val(),
      },
    ];

    student.map((item) => {
      for (var key in item) {
        var son = item[key];
        son === '请选择' && (item[key] = '');
      }
    });

    // var str = '',
    //     maps = []
    // for (var key in student) {
    //     maps.push(key + '=' + student[key])
    // }
    // str = '?' + maps.join('&')

    var self = this;
    var data = {
      student,
      studentEducations: studentEducationList,
      studentOccupations: studentOccupationList,
      studentTitles: studentTitleList,
      studentTrains: studentTrainList,
    };

    if (studentEducationList.length === 0) {
      delete data.studentEducations;
    }

    if (studentOccupationList.length === 0) {
      delete data.studentOccupations;
    }

    if (studentTitleList.length === 0) {
      delete data.studentTitles;
    }

    if (studentTrainList.length === 0) {
      delete data.studentTrains;
    }

    if (Object.keys(data).length === 1) {
      return;
    }

    console.log('data=======', data);
    return;

    $.ajax({
      // url: baseUrl + "studentInfo/saveStudentInfo" + str,
      url: baseUrl + 'studentInfo/saveStudentInfo',
      method: 'Post',
      contentType: 'application/json;charset=UTF-8',
      data: JSON.stringify({
        ...data,
      }),
      headers: {
        Authorization: JSON.parse(localStorage.getItem('userInfo')).token,
      },
      success: function (data) {
        if (data.code === 200) {
          window.uploadId = data.message;
          flag === 'save' ? alert('保存成功') : alert('提交成功');
          flag === 'save'
            ? $('#save').prop('disabled', true)
            : $('#submit').prop('disabled', true);
          self.postFees(student, flag);
        } else {
          alert(data.message);
        }
      },
      error: function (err, res, res1) {
        alert(err.responseJSON.message || '网络错误');
      },
    });
  },
  getFeeInfo(flag) {
    var fees = [];
    // 学历
    $('#xueli .fee:visible').each(function (index) {
      window.trainType = 'education';
      $(this)
        .find('.fee-id')
        .each((_index) => {
          fees.push({
            studentId: window.uploadId,
            commitFlag: flag === 'save' ? 0 : 1,
            businessProgress: 0,
            trainType: 'education',
            // 报考专业
            studyId: window.studentEducationList[index]['id'],
            // 期数
            stage: $(this).find('.fee-id').eq(_index).val(),
            // 缴费日期
            term: $(this).find('.fee-time').eq(_index).val(),
            // 缴费金额
            amount: $(this).find('.fee-money').eq(_index).val(),
            // 是否已缴费
            flag: $(this).find('.fee-flag option:selected').eq(_index).val(),
            // 总费用
            allFee: $(this).parent().find('.zong').eq(index).val(),
            // 优惠费用
            preferentialFee: $(this).parent().find('.youhui').eq(index).val(),
            // 实缴费用
            realPayFee: $(this).parent().find('.shijiao').eq(index).val(),
          });
        });
    });

    // 职业
    $('#zhiye .fee:visible').each(function (index) {
      window.trainType = 'occupation';
      $(this)
        .find('.fee-id')
        .each((_index) => {
          fees.push({
            studentId: uploadId,
            commitFlag: flag === 'save' ? 0 : 1,
            businessProgress: 0,
            trainType: 'occupation',
            studyId: window.studentOccupationList[index]['id'],
            // 期数
            stage: $(this).find('.fee-id').eq(_index).val(),
            // 缴费日期
            term: $(this).find('.fee-time').eq(_index).val(),
            // 缴费金额
            amount: $(this).find('.fee-money').eq(_index).val(),
            // 是否已缴费
            flag: $(this).find('.fee-flag option:selected').eq(_index).val(),
            // 总费用
            allFee: $(this).find('.zong').eq(index).val(),
            // 优惠费用
            preferentialFee: $(this).find('.youhui').eq(index).val(),
            // 实缴费用
            realPayFee: $(this).find('.shijiao').eq(index).val(),
          });
        });
    });

    $('#zhicheng .fee:visible').each(function (index) {
      window.trainType = 'title';
      $(this)
        .find('.fee-id')
        .each((_index) => {
          fees.push({
            studentId: uploadId,
            commitFlag: flag === 'save' ? 0 : 1,
            businessProgress: 0,
            trainType: 'title',
            studyId: window.studentTitleList[index]['id'],
            // 期数
            stage: $(this).find('.fee-id').eq(_index).val(),
            // 缴费日期
            term: $(this).find('.fee-time').eq(_index).val(),
            // 缴费金额
            amount: $(this).find('.fee-money').eq(_index).val(),
            // 是否已缴费
            flag: $(this).find('.fee-flag option:selected').eq(_index).val(),
            // 总费用
            allFee: $(this).find('.zong').eq(index).val(),
            // 优惠费用
            preferentialFee: $(this).find('.youhui').eq(index).val(),
            // 实缴费用
            realPayFee: $(this).find('.shijiao').eq(index).val(),
          });
        });
    });

    $('#peixun .fee:visible').each(function (index) {
      window.trainType = 'train';
      $(this)
        .find('.fee-id')
        .each((_index) => {
          fees.push({
            studentId: uploadId,
            commitFlag: flag === 'save' ? 0 : 1,
            businessProgress: 0,
            trainType: 'train',
            studyId: window.studentTrainList[index]['id'],
            // 期数
            stage: $(this).find('.fee-id').eq(_index).val(),
            // 缴费日期
            term: $(this).find('.fee-time').eq(_index).val(),
            // 缴费金额
            amount: $(this).find('.fee-money').eq(_index).val(),
            // 是否已缴费
            flag: $(this).find('.fee-flag option:selected').eq(_index).val(),
            // 总费用
            allFee: $(this).find('.zong').eq(index).val(),
            // 优惠费用
            preferentialFee: $(this).find('.youhui').eq(index).val(),
            // 实缴费用
            realPayFee: $(this).find('.shijiao').eq(index).val(),
          });
        });
    });

    fees.map((item) => {
      item.teacherId = JSON.parse(
        localStorage.getItem('userInfo')
      ).account.split('-')[1];
      window.studyId = item.studyId;
    });

    return fees;
  },

  postFees(params, flag) {
    var self = this;
    $.ajax({
      url: baseUrl + 'studentInfo/saveStudentFees',
      method: 'post',
      headers: {
        Authorization: JSON.parse(localStorage.getItem('userInfo')).token,
      },
      contentType: 'application/json',
      data: JSON.stringify(this.getFeeInfo(flag)),
      success: function (data) {
        self.postFiles();
      },
    });
  },
  postFiles() {
    if (!window.uploadId) return;
    var files = [];
    var formData = new FormData();
    var maps = {
      'id-front': 'id-front',
      'id-back': 'id-back',
      '1cun': '1cun',
      '2cun': '2cun',
      biyezheng1: 'biyezheng1',
      xueweizheng1: 'xueweizheng1',
      zhucebiao1: 'zhucebiao1',
      biyezheng2: 'biyezheng2',
      xueweizheng2: 'xueweizheng2',
      zhucebiao2: 'zhucebiao2',
      byz: 'byz',
      xwz: 'xwz',
      zh1: $('#zh1').siblings('input').val(),
      zh2: $('#zh2').siblings('input').val(),
      zh3: $('#zh3').siblings('input').val(),
      zh4: $('#zh4').siblings('input').val(),
    };
    $('.input-file').each(function (index) {
      const id = $(this).attr('id');
      if (this.files.length) {
        files.push({
          file: this.files[0],
          key: maps[id],
        });
      }
    });
    // if (!files.length) {
    //   window.location.href = './studentSearch.html';
    //   return;
    // }
    formData.append('studentId', window.uploadId);
    formData.append('studyId', window.studyId);
    formData.append('trainType', window.trainType);
    files.forEach(function (item, index) {
      formData.append('propertys', item.key);
      formData.append('files', item.file);
    });
    $.ajax({
      url: baseUrl + 'studentInfo/uploadStuCertificate',
      method: 'post',
      headers: {
        Authorization: JSON.parse(localStorage.getItem('userInfo')).token,
      },
      data: formData,
      processData: false,
      contentType: false,
      mimeType: 'multipart/form-data',
      success: function (data) {
        window.location.href = './studentSearch.html';
      },
    });
  },
};
info.init();
